/**
 * variables
 * @type {null}
 */
var captchaTippyInstance;
var agreetermTippyInstance;
var emailTippyInstance;
var nickTippyInstance;
var passwordTippyInstance;
var passwordTippyInstance2;

/**
 * functions
 */

function registerCaptchaError(info) {
    captchaTippyInstance.setContent(info);
    captchaTippyInstance.enable();
    captchaTippyInstance.show();
}

function registerAgreetermError(info) {
    agreetermTippyInstance.setContent(info);
    agreetermTippyInstance.enable();
    agreetermTippyInstance.show();
}

function registerEmailError(info) {
    emailTippyInstance.setContent(info);
    emailTippyInstance.enable();
    emailTippyInstance.show();
}

function registerNickError(info) {
    nickTippyInstance.setContent(info);
    nickTippyInstance.enable();
    nickTippyInstance.show();
}

function registerPasswordError(info) {
    passwordTippyInstance.setContent(info);
    passwordTippyInstance.enable();
    passwordTippyInstance.show();
}

function registerPassword2Error(info) {
    passwordTippyInstance2.setContent(info);
    passwordTippyInstance2.enable();
    passwordTippyInstance2.show();
}

$('#register-button').focusout(function () {
    var handle = $('#check-error-result');
    handle.css("display", "none");
});

function registerOnRegisterWithMail () {
    var email = $('#email-input').val();
    var agreeTerms = $('#agreeTerms').is(':checked');
    var captcha = $('#input-captcha').val();
    var clientHash = $('#input-captcha').realperson('getHash');

    if (!validateEmail(email)) {
        registerEmailError('<strong class="text-yellow">输入的电子邮箱格式不正确</strong>');
        return;
    }

    if (agreeTerms == false) {
        registerAgreetermError('<strong class="text-yellow">您必须同意网站使用条款</strong>');
        return;
    }

    if (captcha == null || captcha.trim() == '') {
        registerCaptchaError('<strong class="text-yellow">必须输入图形验证码</strong>');
        return;
    }

    $.ajax(
        {
            type: 'post',
            async: true,
            data: {'email': email, 'clientHash': clientHash, 'captcha':captcha},
            url: document.location.origin + '/api/mailregister',
            dataType:'text',
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    window.location.href = document.location.origin + "/mailregisterresponse?mail=" + URLencode(email);
                }
                else {
                    if (json.result == 1404) {
                        registerCaptchaError(json.description)
                    }
                    else {
                        showAutoDialog(1000, "error", json.description);
                    }
                }
            },
            error: function () {
                console.log("Ajax 发生错误！");
            }
        }
    );
}

function registerOnRegisterWithNick () {
    var nick = $('#input-nick-value').val();
    var password = $('#password-input').val();
    var password2 = $('#password-retype-input').val();
    var agreeTerms = $('#agreeTerms').is(':checked');
    var captcha = $('#input-captcha').val();
    var clientHash = $('#input-captcha').realperson('getHash');

    if (nick == undefined || nick == '') {
        registerNickError('<strong class="text-yellow">昵称不能为空</strong>');
        return;
    }

    if (password == undefined || password == '') {
        registerPasswordError('<strong class="text-yellow">密码输入不能是空</strong>');
        return;
    }

    if (password != password2) {
        registerPassword2Error('<strong class="text-yellow">输入的密码不一致</strong>');
        return;
    }

    if (agreeTerms == false) {
        registerAgreetermError('<strong class="text-yellow">您必须同意网站使用条款</strong>');
        return;
    }

    if (captcha == null || captcha.trim() == '') {
        registerCaptchaError('<strong class="text-yellow">必须输入图形验证码</strong>');
        return;
    }

    var str = JSON.stringify({"account": nick, "password": password});
    var key = makeKey(16);
    var encrypted = CryptoJS.AES.encrypt(str, key).toString();

    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    key = encrypt.encrypt(key);

    $.ajax(
        {
            type: 'post',
            async: true,
            data: {'account': encrypted, 'key': key, 'clientHash': clientHash, 'captcha':captcha},
            url: document.location.origin + '/api/register',
            dataType:'text',
            success: function(data) {
                var json = JSON.parse(data);

                console.log(json.result);
                if (json.result == 200) {
                    setCookie("token", json.token, 30);
                    window.location.href = document.location.origin + "/usercenteraccount";
                }
                else {
                    showAutoDialog(1000, "error", json.description);
                }
            },
            error: function () {
                console.log("Ajax 发生错误！");
            }
        }
    );
}

function registerOnRegisterButtonClick(target) {

    var mailActive = $('#mail-tab-handle').hasClass('active');
    var nickActive = $('#nick-tab-handle').hasClass('active');
    $(target).prop('disabled', true);

    if (mailActive) {
        registerOnRegisterWithMail();
    }
    else if (nickActive) {
        registerOnRegisterWithNick();
    }
}

function init() {
    captchaTippyInstance = tippy(document.querySelector('#input-captcha'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            captchaTippyInstance.hide();
            captchaTippyInstance.disable();
        }
    });
    captchaTippyInstance.hide();
    captchaTippyInstance.disable();

    agreetermTippyInstance = tippy(document.querySelector('#label-agree-term'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            agreetermTippyInstance.hide();
            agreetermTippyInstance.disable();
        }
    });
    agreetermTippyInstance.hide();
    agreetermTippyInstance.disable();

    emailTippyInstance = tippy(document.querySelector('#email-input'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            emailTippyInstance.hide();
            emailTippyInstance.disable();
        }
    });
    emailTippyInstance.hide();
    emailTippyInstance.disable();

    nickTippyInstance = tippy(document.querySelector('#input-nick-value'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            nickTippyInstance.hide();
            nickTippyInstance.disable();
        }
    });
    nickTippyInstance.hide();
    nickTippyInstance.disable();

    passwordTippyInstance = tippy(document.querySelector('#password-input'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            passwordTippyInstance.hide();
            passwordTippyInstance.disable();
        }
    });
    passwordTippyInstance.hide();
    passwordTippyInstance.disable();

    passwordTippyInstance2 = tippy(document.querySelector('#password-retype-input'), {
        animation: 'perspective',
        inertia: true,
        theme: 'translucent',
        onHidden: function() {
            passwordTippyInstance2.hide();
            passwordTippyInstance2.disable();
        }
    });
    passwordTippyInstance2.hide();
    passwordTippyInstance2.disable();
}

$(document).ready(function() {
    Tipped.create('#comment-iconof-register', "下面列出的方式选择其一即可。注册后在后台可以互通。", {skin:'red'});
    $.realperson.setDefaults({length: 5});
    $('#input-captcha').realperson({regenerate:'看不清，更换字符'});

    init();
});
